package cn.picclife.mwx.app.util;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.Signer;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListVersionsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.services.s3.model.S3VersionSummary;
import com.amazonaws.services.s3.model.VersionListing;
@Component
public class AmazonS3Utils {

	@Value("${file.endpoint.url}")
	private static String endpoint;
	
	@Value("${file.access.key}")
	private static String accessKey;
	
	@Value("${file.secret.key}")
	private static String secretkey;
	
	private static AmazonS3Client client = null;
	public static BasicAWSCredentials credentials = null;
	
	static {
		    credentials = new BasicAWSCredentials(accessKey, secretkey);
			ClientConfiguration clientConfig = new ClientConfiguration();
			clientConfig.setProtocol(Protocol.HTTP);
			clientConfig.setMaxErrorRetry(3);
			clientConfig.setConnectionTimeout(501000);
			clientConfig.setSocketTimeout(501000);
			clientConfig.setSignerOverride("S3SignerType");
			
			client = new AmazonS3Client(credentials, clientConfig);
			client.setEndpoint(endpoint);
	}
	
	private AmazonS3Utils() {}
	
	public static AmazonS3Client getAmazonS3Instance() {
		return client;
	}
	
	/***
	 * 创建桶
	 * @param bucketName
	 * @return
	 */
	public static Bucket createBucket(String bucketName) {
		return client.createBucket(bucketName);
	}
	
	/***
	 * 遍历桶列表
	 */
	public static void listBucket() {
		List<Bucket> buckets = client.listBuckets();
		for(Bucket bucket :buckets) {
			System.out.println(bucket.getName()+","+bucket.getOwner()+","+bucket.getCreationDate());
		}
	}
	
	/***
	 * 删除桶
	 * @param bucketName
	 */
//	public static void deleteBucket(String bucketName) {
//		try {
//            System.out.println(" - removing objects from bucket");
//            ObjectListing object_listing = client.listObjects(bucketName);
//            while (true) {
//                for (Iterator<?> iterator =
//                        object_listing.getObjectSummaries().iterator();
//                        iterator.hasNext();) {
//                    S3ObjectSummary summary = (S3ObjectSummary)iterator.next();
//                    client.deleteObject(bucketName, summary.getKey());
//                }
//
//                // more object_listing to retrieve?
//                if (object_listing.isTruncated()) {
//                    object_listing = client.listNextBatchOfObjects(object_listing);
//                } else {
//                    break;
//                }
//            };
//
//            System.out.println(" - removing versions from bucket");
//            VersionListing version_listing = client.listVersions(
//                    new ListVersionsRequest().withBucketName(bucketName));
//            while (true) {
//                for (Iterator<?> iterator =
//                        version_listing.getVersionSummaries().iterator();
//                        iterator.hasNext();) {
//                    S3VersionSummary vs = (S3VersionSummary)iterator.next();
//                    client.deleteVersion(bucketName, vs.getKey(), vs.getVersionId());
//                }
//
//                if (version_listing.isTruncated()) {
//                    version_listing = client.listNextBatchOfVersions(version_listing);
//                } else {
//                    break;
//                }
//            }
//
//            System.out.println(" OK, bucket ready to delete!");
//            client.deleteBucket(bucketName);
//        } catch (AmazonServiceException e) {
//            System.err.println(e.getErrorMessage());
//            System.exit(1);
//        }
//        System.out.println("Done!");
//	}
	
	/***
	 * 关闭连接
	 */
	public void shutdown() {
		if(client!=null) {
			client.shutdown();
		}
	}
	
	/***
	 * 获取文件的下载路径
	 * @param bucketName
	 * @param key
	 * @expireDate
	 * @return
	 */
	/*public static URL getObjectUrl(String bucketName,String key,String expireDate) {
		client.getObject(new GetObjectRequest(bucketName, key));  
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key); 
        if(expireDate!=null) {
        	 Date expirationDate = null;  
             try {  
                 expirationDate = new SimpleDateFormat("yyyy-MM-dd").parse(expireDate);  
             } catch (Exception e) {  
                 e.printStackTrace();  
             }  
             //设置过期时间  
             urlRequest.setExpiration(expirationDate); 
        }
        //生成公用的url  
        URL url = client.generatePresignedUrl(urlRequest); 
        return url;
	}*/
}
